<?php
namespace App\Repos;

use App\Models\Cart;

class CartRepo
{
	public static function  getPages($where=[],$num=10)
	{	   
	  	$list = Cart::select(['id','shop_id','product_id','product_num'])->with('product:id,spec_id,name,thumb,price,weight')->where($where)->paginate($num); 
	  	return $list;     
	}

	public static function create($data)
	{
		// 如果已经存在此商品那么增加商品数量
		$where = array_only($data, ['user_id', 'product_id']);
		$flag = Cart::where($where)->first();
		if($flag) {
			$flag->product_num += 1; 
			$flag->save();
		}
		else {
			$flag = Cart::Create($data);
		} 
		return $flag;
		
	}

	/**
	 * 购物车减少
	 */
	public static function decrease($data)
	{
		$where['user_id']    = $data['user_id'];
		$where['product_id'] = $data['product_id'];
		$cart = Cart::where($where)->first();
		// 购物车必须保留一个
		if($cart->product_num<2) {
			return $cart;			
		} 
		$cart->product_num = $cart->product_num-1;		
		$cart->save();
		return $cart;
	}

	/**
	 * 删除购物车
	 */
	public static function delete($data)
	{
		$rs = Cart::destroy($data['cart_id']);
		if($rs) {
			return true;
		} 
		return false;
	}

	/**
	 * 释放购物车
	 */
	public static function release($where)
	{
		return Cart::where($where)->delete();
	}

	
	
	

	
	
	
}